package com.fhz.day008;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class LoginActivity extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private CheckBox cbRemember;
    private Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        cbRemember = (CheckBox) findViewById(R.id.cb_remember);
        login = (Button) findViewById(R.id.login);

        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        boolean isRem = sp.getBoolean("isRem", false);
        //第一次不读
        if(isRem){
            //读
            String name = sp.getString("name", "");
            String pwd = sp.getString("pwd", "");
            username.setText(name);
            password.setText(pwd);
            cbRemember.setChecked(true);
        }

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(cbRemember.isChecked()){
                    String name = username.getText().toString();
                    String pwd = password.getText().toString();
                    SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("name",name);
                    edit.putString("pwd",pwd);
                    edit.putBoolean("isRem",true);
                    edit.apply();
                }else{
                    SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                }
            }
        });

    }
}